package com.yonyou.iuap.shell.service.impl;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.yonyou.iuap.pub.DateUtil;
import com.yonyou.iuap.pub.IDFactory;
import com.yonyou.iuap.pub.JsonUtils;
import com.yonyou.iuap.shell.dao.BdKnowledgeCategoryEntityDao;
import com.yonyou.iuap.shell.dao.KmAttachmentEntityDao;
import com.yonyou.iuap.shell.dao.KmPublishEntityDao;
import com.yonyou.iuap.shell.entity.BdCategoryRelationEntity;
import com.yonyou.iuap.shell.entity.KmAttachmentEntity;
import com.yonyou.iuap.shell.entity.KmPublishEntity;
import com.yonyou.iuap.shell.entity.exp.AttachementPoJo;
import com.yonyou.iuap.shell.entity.exp.KmpublishPoJo;
import com.yonyou.iuap.shell.entity.exp.KmAttPoJo;
import com.yonyou.iuap.shell.entity.exp.KmpublishPoJo;
import com.yonyou.iuap.shell.pub.IShellDaoEnum;
import com.yonyou.iuap.shell.pub.IShellServiceEnum;
import com.yonyou.iuap.shell.pub.RequestDto;
import com.yonyou.iuap.shell.pub.ResultDto;
import com.yonyou.iuap.shell.service.intf.IKmPublishService;
import com.yonyou.iuap.shell.util.MathUtil3;
@Service(value=IShellServiceEnum.Shell_Service_Publish)
public class KmPublishServiceImpl implements IKmPublishService {
	private final Logger logger = (Logger) LoggerFactory.getLogger(getClass());
	@Autowired
	@Qualifier(IShellDaoEnum.Shell_Dao_KmPublishEntityDao)
	private  KmPublishEntityDao<KmPublishEntity>  kmPublishEntityDao;
	@Autowired
	@Qualifier(IShellDaoEnum.Shell_Dao_KmAttachmentEntityDao)
	private KmAttachmentEntityDao<KmAttachmentEntity> kmAttDao;
	@Autowired
	@Qualifier("Dao-BdKnowledgeCategoryEntityDao")
	private BdKnowledgeCategoryEntityDao<?> bdKnowledgeCategoryEntityDao;
	
	public ResultDto insert(List<KmPublishEntity> listvo) {
		ResultDto rsDto = new ResultDto();
		rsDto.setStatus(0);
		rsDto.setMessage("添加完成!");
		if(listvo!=null && listvo.size()>0){
			for(KmPublishEntity vo : listvo){
				vo.setPk_km_publish(IDFactory.getInstance().getID());
				vo.setDr(0);
				vo.setPk_creator(vo.getPk_publish_user());
				vo.setTs(DateUtil.formatDateTime(new Date()));
				vo.setDtcreate(new Date());
				int i_insert = kmPublishEntityDao.insertSelective(vo);
			}
		}
		return rsDto;
	}
	@Transactional
	public ResultDto update(List<KmPublishEntity> listvo) {
		ResultDto rsDto = new ResultDto();
		rsDto.setStatus(0);
		rsDto.setMessage("更新完成!");
		if(listvo!=null && listvo.size()>0){
			for(KmPublishEntity vo : listvo){
				int i_up = kmPublishEntityDao.updateByPrimaryKeySelective(vo);
			}
		}
		return rsDto;
	}

	public ResultDto deleteByCondition(String whereSql) {
		ResultDto rsDto = new ResultDto();
		if(StringUtils.isEmpty(whereSql)){
			rsDto.setStatus(1);
			rsDto.setMessage("删除条件不能为空!");
		}else{
			int i_del = kmPublishEntityDao.deleteByCondition(whereSql);
			rsDto.setStatus(0);
			rsDto.setMessage("删除完成!");
		}
		return rsDto;
	}

	public ResultDto queryByCondition(String whereSql) {
		ResultDto rsDto = new ResultDto();
		List<KmPublishEntity> listvo = kmPublishEntityDao.selectByCondition(whereSql);
		rsDto.setStatus(0);
		rsDto.setMessage("数据查询成功!");
		rsDto.setNum(listvo==null?0:listvo.size());
		rsDto.setCount(listvo==null?0:listvo.size());
		rsDto.setData(listvo);
		return rsDto;
	}
//	查询知识内容及附件
	public ResultDto queryKnowledgeAttachment(Map<String, String> map) {
		ResultDto rsDto = new ResultDto();
		List<KmAttPoJo> listvo = kmPublishEntityDao.queryKnowledgeAttachment(map);
		rsDto.setStatus(0);
		rsDto.setMessage("数据查询成功!");
		rsDto.setNum(listvo==null?0:listvo.size());
		rsDto.setCount(listvo==null?0:listvo.size());
		rsDto.setData(listvo);
		return rsDto;
	}
//	单独查询知识内容
	public ResultDto queryKnowledgebypk(Map<String, String> map) {
		ResultDto rsDto = new ResultDto();
		List<KmAttPoJo> listvo = kmPublishEntityDao.queryKnowledgebypk(map);
		rsDto.setStatus(0);
		rsDto.setMessage("数据查询成功!");
		rsDto.setNum(listvo==null?0:listvo.size());
		rsDto.setCount(listvo==null?0:listvo.size());
		rsDto.setData(listvo);
		return rsDto;
	}
//	单独查询知识附件
	public ResultDto queryKnowledgeattbypk(Map<String, String> map) {
		ResultDto rsDto = new ResultDto();
		List<KmAttPoJo> listvo = kmPublishEntityDao.queryKnowledgeattbypk(map);
		rsDto.setStatus(0);
		rsDto.setMessage("数据查询成功!");
		rsDto.setNum(listvo==null?0:listvo.size());
		rsDto.setCount(listvo==null?0:listvo.size());
		rsDto.setData(listvo);
		return rsDto;
	}
	public ResultDto queryKmpublishPoJoLike(RequestDto req) {
		ResultDto rsDto = new ResultDto();
		List<KmpublishPoJo> listvo = kmPublishEntityDao.queryKmpublishPoJoLike(req);
		int count_i = kmPublishEntityDao.countKmpublishPoJoLike(req);
		rsDto.setNum(listvo==null?0:listvo.size());
		rsDto.setCount(count_i);
		rsDto.setData(listvo);
		return rsDto;
	}
	
	
	public List<KmpublishPoJo> CountKmpublishPoJo() {
		// TODO 自动生成的方法存根
		NumberFormat PercentFormat = NumberFormat.getPercentInstance();
//		List list=kmPublishEntityDao.selectAll();
		List<KmpublishPoJo>  pojoList=kmPublishEntityDao.CountKmpublishPoJo();
//		for(int i=0;i<pojoList.size();i++){
//			double a =Double.parseDouble(pojoList.get(i).getNuu());
//			pojoList.get(i).setPublish_key(PercentFormat.format(a/list.size()));
//		}
		return pojoList;
	}
	public ResultDto selectpublishtimeasc(RequestDto request) {
		// TODO 自动生成的方法存根
		ResultDto rsDto = new ResultDto();
		List listvo = kmPublishEntityDao.selectPublishPage(request);
		rsDto.setStatus(0);
		rsDto.setMessage("数据查询成功!");
		rsDto.setNum(listvo==null?0:listvo.size());
		rsDto.setCount(listvo==null?0:listvo.size());
		rsDto.setData(listvo);
		return rsDto;
	}
	public ResultDto queryKmpublishfavoarite() {
		// TODO 自动生成的方法存根
		ResultDto rsDto = new ResultDto();
		List listvo = kmPublishEntityDao.queryKmpublishfavoarite();
		rsDto.setStatus(0);
		rsDto.setMessage("数据查询成功!");
		rsDto.setNum(listvo==null?0:listvo.size());
		rsDto.setCount(listvo==null?0:listvo.size());
		rsDto.setData(listvo);
		return rsDto;
	}
	public ResultDto queryKmpublishfavoaritecomment() {
		// TODO 自动生成的方法存根
		ResultDto rsDto = new ResultDto();
		List listvo = kmPublishEntityDao.queryKmpublishfavoaritecomment();
		rsDto.setStatus(0);
		rsDto.setMessage("数据查询成功!");
		rsDto.setNum(listvo==null?0:listvo.size());
		rsDto.setCount(listvo==null?0:listvo.size());
		rsDto.setData(listvo);
		return rsDto;
	}
	
	/**
	 * 条件查询知识库列表 （分页 ） -------------- 
	 */
	public ResultDto queryKmpublishPoJoLikePc(Map map) {
		ResultDto rsDto = new ResultDto();
		String keyWord=(String) map.get("publish_key");  			//查询条件
		String km_type=(String) map.get("km_type");					//知识列别PK
		String paramOrder= (String) map.get("paramOrder");  			//排序字段
		String orderRule = (String) map.get("orderRule");   			//排序规则 ASC或者 DESC	
		List<String> pk_knowledge_category=(List<String>) map.get("pk_category");
		
		RequestDto red =new RequestDto();
		int pageNum=panduan(map).get("pageNum").intValue();
		int pageSize=panduan(map).get("pageSize").intValue();
		pageNum=(pageNum-1) * pageSize;
		red.setPageNum(pageNum);
		red.setPageSize(pageSize);
		
		//查询里的条件
		
		StringBuffer paramKeyWord=new StringBuffer();
//		类别条件
		if(km_type != null && !km_type.equals("")){
			String s="(select t.pk_knowledge_category from SHELL_BD_KNOWLEDGE_CATEGORY t "
					+ "where t.pk_knowledge_category='"+km_type+"' or t.fw_parent='"+km_type+"')";
			paramKeyWord.append(" AND km_type in "+s);
		}
		//ORACLE方言，目前只能写死
		if(!StringUtils.isEmpty(keyWord)){
			if(keyWord.endsWith(",")){
				keyWord.substring(0, keyWord.length()-1);
			}
//			在汉字与英文字母中间插入空格
			keyWord=keyWord.replaceAll("([\\u4e00-\\u9fa5])(\\w)", "$1 $2");
//			在数字和字母之间插入空格
			keyWord=keyWord.replaceAll("([0-9])([A-Za-z])", "$1 $2");
			String[] keylist=keyWord.trim().split("\\s+");
			for(String key:keylist){
				paramKeyWord.append(" AND upper(c.publish_key) like upper('%"+key+"%')");
			}
		}
		//类别管理员可维护的知识
		if(pk_knowledge_category!=null&&pk_knowledge_category.size()>0){
			StringBuffer pklist=new StringBuffer();
			for(String pk:pk_knowledge_category){
				pklist.append("'"+pk+"',");
			}
			pklist.deleteCharAt(pklist.length()-1);
			paramKeyWord.append(" AND u.pk_knowledge_category in ("+pklist.toString()+")");
		}
		String countSql = paramKeyWord.toString();
		if(paramOrder != null && !paramOrder.equals("")){
			paramKeyWord.append(" ORDER BY ").append(" "+paramOrder+" ");
			if(orderRule != null && !orderRule.equals("")){
				paramKeyWord.append(orderRule);
			}else{
				paramKeyWord.append("  ASC  ");
			}
		}
		
		//子查询里的条件
//		StringBuffer parkey=new StringBuffer();
//		if(!StringUtils.isEmpty(keyWord)){
//			if(keyWord.endsWith(",")){
//				keyWord.substring(0, keyWord.length()-1);
//			}
//			String[] keylist=keyWord.split(",");
//			for(String key:keylist){
//				parkey.append(" AND upper(c.publish_key) like upper('%"+key+"%') ");
//			}
//		}
		
		Map<String, Object> parmMap = new HashMap<String, Object>();
		parmMap.put("paramKeyWord", paramKeyWord.toString());  
//		parmMap.put("parkey", parkey.toString());
		
		red.setParmMap(parmMap);
		red.setPk_user((String) map.get("pk_user"));
		logger.info("queryKmpublishPoJoLikePc查询参数"+JsonUtils.toJsonStr(red));
		//查询
		List<KmpublishPoJo> listvo = kmPublishEntityDao.queryKmpublishPoJoLikePc(red);
		rsDto.setNum(listvo==null?0:listvo.size()); //本次查询的数据量
		parmMap.put("paramKeyWord", countSql);
		rsDto.setCount(kmPublishEntityDao.queryKmpublishPoJoLikePcCount(red));  //分页所有条数
		rsDto.setData(listvo);
		return rsDto;
	}
	
	/**
	 * 知识库列表 修改记录 封存标志     是否启用      Y启用   N禁用
	 */
	public ResultDto updateSealmark(Map<String, String> map) {
		ResultDto rt=new ResultDto();
		KmPublishEntity kp = new KmPublishEntity();
		String fale = map.get("fale");  // fale=btn-unlock 启用　　　＝btn-disable　禁用　 
		String zsid  = map.get("zsid");  // 知识id
		kp.setPk_km_publish(zsid);
		if("btn-unlock".equals(fale)){
			kp.setSealmark("N");
			rt.setNum(2);
		}else{
			kp.setSealmark("Y");
			rt.setNum(3);
		}
		int count = kmPublishEntityDao.updateKmPublishEntityTj(kp);
		if(count > 0){
			rt.setStatus(0);
			rt.setMessage("数据修改成功!");
		}else{
			rt.setStatus(1);
			rt.setMessage("数据修改失败!");
		}
		return rt;
	}
	
	/**
	 *  知识修改前 拉取当前要修改的知识信息
	 *  @param map.pk_km_publish  知识id
	 */
	public ResultDto updatePublishFront(Map<String, String> map) {
		ResultDto rt=new ResultDto();
		String pk_km_publish = map.get("pk_km_publish").toString(); //知识id
		if(pk_km_publish == null || pk_km_publish.equals("")){
			rt.setStatus(2);
			rt.setMessage("查询条件不允许为空!");
		}
		KmpublishPoJo kmblpo=kmPublishEntityDao.updatePublishFront(pk_km_publish);
		if(kmblpo != null ){
			rt.setStatus(0);
			rt.setData(kmblpo);
			rt.setMessage("数据查询成功!");
		}else{
			rt.setStatus(1);
			rt.setMessage("数据查询失败!");
		}	
		return rt;
	}
	
	/**
	 * 删除发布的知识
	 * @param parMap.pk_km_publish  知识id
	 * @return
	 */
	public ResultDto delPublishByid(Map<String, String> map) {
		ResultDto rt=new ResultDto();
		String pk_km_publish = map.get("pk_km_publish").toString(); //知识id
		if(pk_km_publish == null || pk_km_publish.equals("")){
			rt.setStatus(2);
			rt.setMessage("查询条件不允许为空!");
		}
		
		int  a=kmPublishEntityDao.deleteByPrimaryKey(pk_km_publish);  //删除发布的知识
		if(a > 0){
			int  b = kmPublishEntityDao.deleteByPrimaryKeyComment(pk_km_publish);  //删除知识下的所有评论
			rt.setStatus(0);
			rt.setMessage("数据删除成功!");
			return rt;
		}
		rt.setStatus(1);
		rt.setMessage("数据删除失败!");
		return rt;
	}
	
	/**
	 * #######  新增知识 
	 */
	@Transactional
	public ResultDto insertPublishEntity(Map<String, String> map) {
		ResultDto rt=new ResultDto();
		KmPublishEntity pe=new KmPublishEntity();
		pe.setPk_km_publish(MathUtil3.uuid32());
		pe.setKm_type(map.get("km_type"));					//知识类别id
		pe.setPk_publish_user(map.get("pk_publish_user"));  //发布不人id
		pe.setDtcreate(new Date());
		pe.setPublish_time(DateUtil.formatDateTime(new Date()));//发布时间
		pe.setPublish_title(map.get("publish_title"));	    //知识标题
		pe.setPublish_key(map.get("publish_key"));	   		//关键字
		pe.setPublish_memo(map.get("publish_memo"));  		//知识摘要
		pe.setSealmark("Y");
		pe.setStudio_url(map.get("studio_url"));			// 字段存储视频地址
		//新增上传文件
		String new_files = map.get("files_new");
		//删除文件
		String del_files = map.get("files_del");
		int count = kmPublishEntityDao.insertSelective(pe); //持久化文章表
		BdCategoryRelationEntity relation = new  BdCategoryRelationEntity();
		relation.setPk_category_relation(MathUtil3.uuid32()); 					//主键id
		relation.setPk_user(map.get("pk_publish_user")); 						// 用户id
		relation.setPk_knowledge_category(map.get("km_type"));  			//类型id
		relation.setSealmark("Y");  										  //是否禁用    Y 启用
		relation.setPk_creator(map.get("pk_publish_user"));  				//当前登录用户id
		relation.setDtcreate(new Date());									//当前登录时间
		
		int relationCount=bdKnowledgeCategoryEntityDao.insertRelation(relation);  //持久化从表数据
		if(relationCount > 0 ){
			//修改附件表数据
			if(!StringUtils.isEmpty(new_files)){
				for(String str : new_files.split(",")){
					KmAttachmentEntity attvo = new KmAttachmentEntity();
					attvo.setPk_attachment(str);
					attvo.setPk_uploaduser(pe.getPk_publish_user());
					attvo.setPk_business(pe.getPk_km_publish());
					kmAttDao.updateByPrimaryKeySelective(attvo);
				}
			}
			//删除附件表信息
			if(!StringUtils.isEmpty(del_files)){
				for(String str : del_files.split(",")){
					kmAttDao.deleteByPrimaryKey(str);
				}
			}
			rt.setStatus(0);
			rt.setMessage("数据添加成功!");
		}else {
			rt.setStatus(1);
			rt.setMessage("数据添加失败!");
		}
		return rt;
	}
	
	public ResultDto updatePublishEntity(Map<String, String> map) {
		ResultDto rt=new ResultDto();
		KmPublishEntity pe=new KmPublishEntity();
		pe.setPk_km_publish(map.get("pk_km_publish"));		//知识主键id
		pe.setKm_type(map.get("km_type"));					//知识类别id
		pe.setUpate_user(map.get("pk_publish_user"));  		//发布不人id
		pe.setUpdate_date(DateUtil.formatDateTime(new Date()));
		pe.setPublish_title(map.get("publish_title"));	    //知识标题
		pe.setPublish_key(map.get("publish_key"));	   		//关键字
		pe.setPublish_memo(map.get("publish_memo"));  		//知识摘要
		pe.setStudio_url(map.get("studio_url"));	//视频地址
		
		//新增上传文件
		String new_files = map.get("files_new");
		//删除文件
		String del_files = map.get("files_del");
		int count = kmPublishEntityDao.updateKmPublishEntityTj(pe);
		if(count > 0 ){
			//修改附件表数据
			if(!StringUtils.isEmpty(new_files)){
				for(String str : new_files.split(",")){
					KmAttachmentEntity attvo = new KmAttachmentEntity();
					attvo.setPk_attachment(str);
					attvo.setPk_uploaduser(pe.getPk_publish_user());
					attvo.setPk_business(pe.getPk_km_publish());
					kmAttDao.updateByPrimaryKeySelective(attvo);
				}
			}
			//删除附件表信息
			if(!StringUtils.isEmpty(del_files)){
				for(String str : del_files.split(",")){
					kmAttDao.deleteByPrimaryKey(str);
				}
			}
			rt.setStatus(0);
			rt.setMessage("数据修改成功!");
		}else {
			rt.setStatus(1);
			rt.setMessage("数据修改失败!");
		}
		return rt;
	}
	
	
	/**
	 *  条件查询知识库列表 参数判定方法
	 * @param map
	 * @return
	 */
	private Map<String,Integer> panduan(Map map){
		int pageNum=0;
		int pageSize=0;
		String n=String.valueOf(map.get("pageNum"));
		String s=String.valueOf(map.get("pageSize"));
		if(n == null){
			n="";
		}
		if(s == null ){
			s="";
		}
		if(n.equals("")){
			pageNum++;
		}else {
			pageNum=Integer.parseInt(n);
		}
		if(s.equals("")){
			pageSize=15;
		}else{
			pageSize=Integer.parseInt(s);
		}
		if(pageNum == 0){
			pageNum++;
		}
		if(pageSize == 0){
			pageSize=15;
		}
		Map<String,Integer> mapin =new HashMap<String, Integer>();
		mapin.put("pageNum", pageNum);
		mapin.put("pageSize", pageSize);
		return mapin;
	}
	public void updateKey(Map<String, String> map) {
		kmPublishEntityDao.updateKey(map);
	}
	

}
